import time

import execjs
import requests

session = requests.Session()

session.headers = {'user-agent': 'yuanrenxue.project'}
# session.cookies.update({, })
session.cookies.set('sessionid', 'hc54r4fale2u0lh27lpu019lo086knu8')


def fetch(page):
    with open('main_sync.js', 'r', encoding='utf-8') as f:
        js_file = f.read()
    ctx = execjs.compile(js_file)
    m = ctx.call('run')
    url = f'https://match.yuanrenxue.cn/api/match/15?page={page}&m={m}'
    response = session.get(url,
                           proxies={
                               'http': 'http://127.0.0.1:7890',
                               'https': 'http://127.0.0.1:7890'
                           }
                           )
    data = response.json()
    return [item['value'] for item in data['data']]

    # print(response.text)


def average(lst):
    total = sum(lst)
    return total / len(lst)


def main():
    res = []
    for page in range(1, 6):
        res.extend(fetch(page))
        time.sleep(1)
    print(res)
    print(sum(res))


# 任务十五：抓取这5页的数字，计算加和并提交结果
if __name__ == '__main__':
    main()
    # a = [8179, 6177, 4174, 5945, 9556, 2318, 4, 2653, 4855, 1370, 2366, 2108, 6159, 5685, 2010, 7109, 1002, 9300, 8995, 5732, 5535, 7126, 7472, 4129, 2724, 3475, 3605, 7729, 1860, 833, 3937, 6420, 115, 4333, 6674, 383, 5922, 7344, 7012, 8009]
